package main.chapter6

import main.chapter6.async.asyncCoroutine
import main.chapter6.async.startDownloadImage
import main.chapter6.async.startTimeConsumingOperations
import javax.swing.WindowConstants

//下载图片的Url
const val LOGO_URL = "https://www.imooc.com/static/img/index/logo.png"

fun main() {
    val frame = MainWindow()
    frame.title = "协程演示"
    frame.setSize(300, 200)
    frame.isResizable = true
    frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
    frame.init()
    frame.isVisible = true

    frame.onClickButton {
        log("协程之前")
        //开始协程
        asyncCoroutine {
            log("开始协程")
            //开始下载图片
            val image = startTimeConsumingOperations {
                startDownloadImage(url = LOGO_URL)
            }
            log("拿到图片")
            frame.setLogo(image)
        }
        log("协程之后")
    }
//    frame.onClickButton {
//        try {
//            downloadService(url = LOGO_URL, response = object : Response {
//                override fun getResponse(result: ByteArray) {
//                    //切换到主线程进行UI操作
//                    SwingUtilities.invokeLater {
//                        frame.setLogo(result)
//                    }
//                }
//            })
//        } catch (e: MalformedURLException) {
//            e.printStackTrace();
//        } catch (e: IOException) {
//            e.printStackTrace();
//        }
//    }
}